var nVehiculo = 60;
var inicio = false;

$(document).ready(main);

function main(){
    $("#realizarSimulacion").click(initSimulacion);
    $("#pararSimulacion").click(stopSimulacion);
}

function initSimulacion(){    
    inicio = true;
}

function stopSimulacion(){
    inicio = false;
}

var motorG = {
        reloj:[1],
        fecha:[1],
	mapHeight: 100010,
	mapWidth: 150010,
	nodeDistance: 1000,
	nodeRadius: 70,
	numNodesX:150,
	numNodesY:100,
	nodeArray:[],
        incidenciaArray:[],
        nVehiculosUsados:0,        
        diasSimulados:1,
        inactivo:false,
	initNodeArray: function(){
		for(var i = 0; i< this.numNodesX;i++){
			for(var j=0; j< this.numNodesY;j++){
				this.nodeArray.push(new Node(this.nodeRadius+i*this.nodeDistance,
				this.nodeRadius+j*this.nodeDistance));
			}
		}
	},
	vehicleArray:[],
	initVehicleArray: function(){
		this.vehicleArray = [];
                total = parseInt($("#numCarro").attr("value")) + parseInt($("#numMoto").attr("value"));
                //alert(total);
		for(var i=0; i < total;i++){
                    if(i < document.getElementById("lblNumcarro"))
			this.vehicleArray.push(new Vehicle(45000,30000,this.images[1],i,1));
                    else this.vehicleArray.push(new Vehicle(45000,30000,this.images[0],i,2));
		}
                console.log(this.vehicleArray);
	},
//        initMotoArray: function(){
//		this.vehicleArray = [];
//		for(var i=0; i < 20;i++){
//			this.vehicleArray.push(new Vehicle(45000,30000,this.images[1],i));
//		}
//	},        
	images :[],
        pedidoArray:[],
        bloqueoArray:[],
	imgCount :0,
	imagesLoaded: false,
	loadImages : function(){
            if(inicio){
                var carImage = new Image();
                var motorBikeImage = new Image();
                var incidenciaImage = new Image();
                carImage.onload = function(){
                    motorG.images.push(this);
                    motorG.imgCount++;
                    motorG.images.push(motorBikeImage);
                    motorG.images.push(incidenciaImage);
                    motorG.imgCount++;
//                    motorG.images.push(this);
//                    motorG.imgCount++;
                    motorG.imagesLoaded = true;
                    if(motorG.imagesLoaded){
                        motorG.initVehicleArray();
                        motorG.timer = setInterval(updatePositions,600); 
                        visualizer.draw();
                    }
                };
                carImage.src = "resources/car.svg";
                motorBikeImage.src = "resources/motorbike.svg" ;
                incidenciaImage.src = "resources/incidencia.svg";
    //                var motorBikeImage = new Image();
    //                motorBikeImage.onload = function(){
    //                    motorG.images.push(this);
    //                    motorG.imgCount++;
    //                    if (motorG.imagesLoaded){
    //                        motorG.initMotoArray();
    //                        motorG.timer = setInterval(updatePositions,400);
    //                        visualizer.draw();
    //                    }
    //                };
    //                motorBikeImage.src = "resources/motorbike.svg" ;
                    //wareHouse.src = "resources/motorbike.svg";
//                var motorBikeImage = new Image();
//                motorBikeImage.onload = function(){
//                    motorG.images.push(this);
//                    motorG.imgCount++;
//                    if(motorG.imagesLoaded){
//                        motorG.initVehicleArray();
//                        motorG.timer = setInterval(updatePositions,400); 
//                        visualizer.draw();
//                    }            
//                };
//                motorBikeImage.src = "resources/motorbike.svg" ;
            }
        }
};

function Rect(x,y,w,h){
	this.x=x;
	this.y=y;
	this.w=w;
	this.h=h;
}

function Canvas(canvas){
	this.canvas = canvas;
	this.ctx = canvas.getContext("2d");
	this.dirtyRects =[];
}

Canvas.prototype ={
	canvas: null,
	ctx:null,
	dirtyRects:[],
	clearCanvas : function(){
		var rect;
		while(this.dirtyRects.length !== 0){
			rect = this.dirtyRects.pop();
			this.ctx.clearRect(rect.x,rect.y,rect.w,rect.h);
		}
	}
};

function Node(x,y){
	this.x =x;
	this.y =y;
}

Node.prototype ={
	x:0,
	y:0,
	borderColor:'#606060',
	fillColor:'#AAAAAA',
	streetColor:'#DDDDDD',
	streetBorderColor:"#000000",
	radius:motorG.nodeRadius,
	canvasX:0,
	canvasY:0,
	canvasRadius:0,
	canvasDistance:0,
	draw: function(visualizer){
		var ctx = motorG.mapCanvas.ctx;
		this.canvasX = (this.x - visualizer.x) * visualizer.ratio;
		this.canvasY = (this.y - visualizer.y) * visualizer.ratio;
		this.canvasRadius = this.radius*visualizer.ratio;
		this.canvasDistance = motorG.nodeDistance*visualizer.ratio;
		//dibujar las 2 calles
		ctx.fillStyle = this.streetColor;
		ctx.beginPath();
		ctx.rect(this.canvasX,this.canvasY - (this.canvasRadius /2),this.canvasDistance,this.canvasRadius);
		ctx.fill();
		motorG.mapCanvas.dirtyRects.push(new Rect(this.canvasX-1,this.canvasY - (this.canvasRadius /2)-1,this.canvasDistance+2,this.canvasRadius+2));
		
		ctx.beginPath();
		ctx.rect(this.canvasX - (this.canvasRadius /2),this.canvasY,this.canvasRadius,this.canvasDistance);
		ctx.fill();
		motorG.mapCanvas.dirtyRects.push(new Rect(this.canvasX - (this.canvasRadius /2)-1,this.canvasY-1,this.canvasRadius +2,this.canvasDistance+2));
		//dibujar el circulo
		ctx.beginPath();
		ctx.arc(this.canvasX,this.canvasY,this.canvasRadius,0,360,true);
		ctx.strokeStyle=this.borderColor;
		ctx.stroke();
		ctx.fillStyle = this.fillColor;
		ctx.fill();
		motorG.mapCanvas.dirtyRects.push(new Rect(this.canvasX-this.canvasRadius -1,this.canvasY-this.canvasRadius -1,this.canvasRadius*2 +2,this.canvasRadius*2+2));
		
	}
};

function Vehicle(x,y,img,i,tipo){
	this.x=x;
	this.y=y;
	this.sprite = img;
        this.id = i;
        this.i = i;
        this.tipo = tipo;
}

function Pedido(x,y,cp,minutosRestantes,idPedido){
    this.x=x;
    this.y=y;
    this.cantPaq = cp;
    this.minRest = minutosRestantes;
    this.idPedido = idPedido;
}

function Bloqueo(x,y){
    this.x=x;
    this.y=y;
}

Bloqueo.prototype= {
    x:0,
    y:0,
    side:700,
    draw: function (visualizer){
        var ctx = motorG.vehicleCanvas.ctx;
        var canvasX = (this.x - visualizer.x - this.side/2 + motorG.nodeRadius/2) * visualizer.ratio;
        var canvasY = (this.y - visualizer.y) * visualizer.ratio;
        ctx.fillStyle = "#FF0000";
        ctx.beginPath();
        ctx.rect(canvasX,canvasY, this.side*visualizer.ratio,this.side*visualizer.ratio);
        ctx.fill();
    }
};

function Incidencia(x,y){
    this.x=x;
    this.y=y;
    this.sprite = motorG.images[2];
}

Incidencia.prototype= {
    x:0,
    y:0,
    width:1500,
    heigth:1500,
    side:1500,
    draw: function (visualizer){
        var ctx = motorG.vehicleCanvas.ctx;
        var canvasX = (this.x - visualizer.x - this.side/2 + motorG.nodeRadius/2) * visualizer.ratio;
        var canvasY = (this.y - visualizer.y) * visualizer.ratio;
        ctx.drawImage(motorG.images[2],canvasX-3,canvasY-3, this.width*visualizer.ratio+6,this.heigth*visualizer.ratio+6);
    }
};

Pedido.prototype= {
    x:0,
    y:0,
    cantPaq:0,
    prioridad:10,
    minRest:0,
    side: 700,
    idPedido:0,
    draw: function (visualizer){
        var ctx = motorG.vehicleCanvas.ctx;
        var canvasX = (this.x - visualizer.x - this.side/2 + motorG.nodeRadius/2) * visualizer.ratio;
	var canvasY = (this.y - visualizer.y) * visualizer.ratio;
        ctx.fillStyle = "#0000FF";
        ctx.beginPath();
	ctx.rect(canvasX,canvasY, this.side*visualizer.ratio,this.side*visualizer.ratio);
        ctx.fill();
    }
};

Vehicle.prototype ={
	x:0,
	y:0,
        placa: "",
	width:motorG.nodeRadius*4,
	heigth:motorG.nodeRadius*4 *0.7,
	type: "auto",
        tipo:0,
        id:0,
        pedidos:[],
        minutosRestantes:0,
	sprite: motorG.images[this.tipo],
        routeColor: "#DDDDDD",
        coloresRuta: ["#44944A","#7B005B","#355E3B","#0000FF","#002FA7","#000080","#0047AB","#0131B4","#4B0082","#003153",
                      "#FF0000","#DC143C","#E34233","#800000","#00FF00","#4CBB17","#6B8E23","#50C878","#00A86B","#40826D",
                      "#6050DC","#FF00FF","#FD3F92","#C54B8C","#E0B0FF","#C8A2C8","#FEC3AC","#E6E6FA","#FFC0CB","#00FFFF",
                      "#30D5C8","#87CEFF","#9BC4E2","#7FFFD4","#FFFF00","#FDE910","#FFD700","#FFBF00","#E3A857","#FFBA00",
                      "#964B00","#94812B","#CC7722","#B87333","#DA8A5F","#800020","#8B00FF","#B57EDC","#9966CC","#660099",
                      "#66023C","#FF7028","#FF7F50","#FF8C69","#FBCEB1","#F5DEB3","#FFC8A0","#C0C0C0","#808080","#996600"],
	ruta : [],
	draw : function(visualizer){
                //this.tipo = tipo;
		var ctx = motorG.vehicleCanvas.ctx;
		var canvasX = (this.x - visualizer.x - this.width/2 + motorG.nodeRadius/2) * visualizer.ratio;
		var canvasY = (this.y - visualizer.y) * visualizer.ratio;
                //console.log(motorG.images[tipo-1],tipo);
		ctx.drawImage(motorG.images[tipo-1],canvasX-3,canvasY-3, this.width*visualizer.ratio+6,this.heigth*visualizer.ratio+6);
		this.drawRoutes(visualizer);
		motorG.vehicleCanvas.dirtyRects.push(new Rect(canvasX-4,canvasY-4, this.width*visualizer.ratio+8,this.heigth*visualizer.ratio+8));
	},
	drawRoutes: function(visualizer){
                
                document.getElementById("dia").innerHTML = "<h4> DIA "+ motorG.diasSimulados + "</h4>";
                document.getElementById("fecha").innerHTML = "Fecha Simulada: "+motorG.fecha[0];               
                                 
                document.getElementById("hora").innerHTML = "Hora Simulada: "+motorG.reloj[0];
                //Muestra el turno en que se encuentra
                if (motorG.reloj[0] < "08:00"){                    
                    document.getElementById("turno").innerHTML = "Turno Ma&ntilde;ana";
                }else
                    if (motorG.reloj[0] < "16:00"){
                        document.getElementById("turno").innerHTML = "Turno Tarde";
                    }else
                    document.getElementById("turno").innerHTML = "Turno Noche";
                
                
                if (document.getElementById("pedidosDIV") !== null){
                    if (this.pedidos.length){
                    document.getElementById("pedidosDIV").innerHTML += "<div class=\"accordion-group\">";
                    document.getElementById("pedidosDIV").innerHTML += "<div class=\"accordion-heading\">";
                    document.getElementById("pedidosDIV").innerHTML += "<a class=\"accordion-toggle\" data-toggle=\"collapse\" data-parent=\"#accordion2\" href=\"#collapse" + this.id + "\">";
                    document.getElementById("pedidosDIV").innerHTML += "Vehiculo con placa: "+this.placa;
                    document.getElementById("pedidosDIV").innerHTML += "</a></div>";
                    document.getElementById("pedidosDIV").innerHTML += "<div id=\"collapse" + this.placa + "\" class=\"accordion-body collapse in\">";
                    document.getElementById("pedidosDIV").innerHTML += "<div class=\"accordion-inner\">";
                    motorG.nVehiculosUsados ++;//se aumentan los vehiculos usados
                    for(var i=0;i<this.pedidos.length;i++){
                        //if (this.pedidos[i].minRest  < 0 ){
                            //alert(this.pedidos[i].idPedido + "  -  (" + this.pedidos[i].x + "," + this.pedidos[i].y + ") " + "T = " + this.pedidos[i].minRest);
                            document.getElementById("pedidosDIV").innerHTML += "Pedido " + i + ": x = " + this.pedidos[i].x + ", y = " + this.pedidos[i].y + "<br>";
                            document.getElementById("pedidosDIV").innerHTML += "Numero de paquetes = " + this.pedidos[i].cantPaq + "<br>" + "Minutos restantes: " + this.pedidos[i].minRest + "<br>";
                            //if (this.tipo)
                            if (this.pedidos[i].minRest > 0){
                            document.getElementById("pedidosDIV").innerHTML += "Distancia restante = " +  (this.pedidos[i].minRest * 30/60) + " km<br>";
                            }
                            document.getElementById("pedidosDIV").innerHTML += "---------------------------------------<br>";
                       // }   
                    }


                    document.getElementById("pedidosDIV").innerHTML += "</div></div></div>";
                    }
                }
		for(var i =0; i < this.ruta.length -1;i++){
			this.drawSegment(this.ruta[i],this.ruta[i+1],visualizer,this.coloresRuta[this.id]);
		}
                

	},
	drawSegment: function(n1,n2,v,color){
		var ctx = motorG.vehicleCanvas.ctx;
		var canvasX = (n1.x - v.x) * v.ratio;
		var canvasY = (n1.y - v.y) * v.ratio;
		var canvasRadius = n1.radius*v.ratio;
		var canvasDistance = motorG.nodeDistance*v.ratio;
		ctx.fillStyle = color;
		ctx.beginPath();
		var h,w;

		if(n2.x !== n1.x){
			canvasY -= canvasRadius /2;
			h = canvasRadius;
			var sign = n2.x < n1.x ? -1:1;
			w = canvasDistance * sign;
		}
		else{
			canvasX -= canvasRadius /2;
			w = canvasRadius;
			var sign = n2.y < n1.y ? -1:1;
			h = canvasDistance * sign;
		}
		ctx.rect(canvasX-1,canvasY-1,w+2,h+2);
		ctx.fill();                
	}
};

function Visualizer(x,y,w,h){
	this.x =x;
	this.y =y;
	this.w=w;
	this.h=h;

	this.nodeIsContained= function(node){
		var xConstraint = (node.x >= (this.x - node.radius) )&& 
		(node.x <= (this.x + this.w + node.radius) );
		var yConstraint = (node.y >= (this.y - node.radius) )&& 
		(node.y <= (this.y + this.h + node.radius) );
		return xConstraint || yConstraint; 
	};

	this.vehicleIsContained = function(v){
		var xConstraint = (v.x + v.width >=(this.x )) &&
		(v.x <= (this.x + this.w));
		var yConstraint = (v.y + v.height  >= (this.y) )&& 
		(v.y <= (this.y + this.h ) );
		return xConstraint || yConstraint; 
	};

	this.draw= function(){
		this.ratio = motorG.mapCanvas.canvas.width/this.w;
		for(var i =0; i < motorG.nodeArray.length;i++){
			var n = motorG.nodeArray[i];
			if(this.nodeIsContained(n)){
				//n.draw(this);
			}
		}
		//motorG.mapCanvas.dirtyRects.push(new Rect(0,0,motorG.mapCanvas.canvas.width,motorG.mapCanvas.canvas.height));
		motorG.vehicleCanvas.dirtyRects.push(new Rect(0,0,motorG.vehicleCanvas.canvas.width,motorG.vehicleCanvas.canvas.height));
		for(var i=0; i < nVehiculo;i++){
			var v = motorG.vehicleArray[i];
			if(this.vehicleIsContained(v)){
				v.draw(this);
			}
		}
	};
        this.drawUpdates = function() {
            //motorG.mapCanvas.dirtyRects.push(new Rect(0,0,motorG.mapCanvas.canvas.width,motorG.mapCanvas.canvas.height));
            motorG.vehicleCanvas.dirtyRects.push(new Rect(0, 0, motorG.vehicleCanvas.canvas.width, motorG.vehicleCanvas.canvas.height));
            if (document.getElementById("pedidosDIV") !== null) {
                document.getElementById("pedidosDIV").innerHTML = "";
            }
            motorG.nVehiculosUsados = 0;
            for (var i = 0; i < nVehiculo; i++) {
                var v = motorG.vehicleArray[i];
                if (this.vehicleIsContained(v)) {
                    v.draw(this);
                }
            }
            if (document.getElementById("pedidosDIV") !== null) {
                document.getElementById("pedidosDIV").innerHTML = "<h5>Vehiculos Totales usados: " + motorG.nVehiculosUsados + "</h5>" + "<h5>Lista:</h5>" + document.getElementById("pedidosDIV").innerHTML;
                vehiculosInactivos = 60 - motorG.nVehiculosUsados;
                document.getElementById("pedidosDIV").innerHTML = "<h5>Vehiculos Inactivos: " + vehiculosInactivos + "</h5>" + document.getElementById("pedidosDIV").innerHTML;
            }
            for (var i = 0; i < motorG.pedidoArray.length; i++) {
                var ped = motorG.pedidoArray[i];
                ped.draw(this);
            }
            for (var i = 0; i < motorG.bloqueoArray.length; i++) {
                var bloq = motorG.bloqueoArray[i];
                bloq.draw(this);
            }
            for (var i = 0; i < motorG.incidenciaArray.length; i++) {
                var inci = motorG.incidenciaArray[i];
                inci.draw(this);
            }
    };
}


function procesandoData(stringJson) {
    var myobject = JSON.parse(stringJson);
    for (var i = 0; i < myobject.vehiculos.length; i++) {
        motorG.vehicleArray[i].x = myobject.vehiculos[i].x*motorG.nodeDistance; // el vehiculo i del arreglo de vehiculos
        motorG.vehicleArray[i].y = myobject.vehiculos[i].y*motorG.nodeDistance;
        motorG.vehicleArray[i].placa = myobject.vehiculos[i].placa;
        motorG.vehicleArray[i].tipo = myobject.vehiculos[i].tipo;
        //alert(motorG.vehicleArray[0].x);
        //crea lista de rutas
        motorG.vehicleArray[i].ruta =[];
        motorG.vehicleArray[i].pedidos =[];
        for (var j = 0; j < myobject.vehiculos[i].ruta.length; j++) {
            node = motorG.nodeArray[myobject.vehiculos[i].ruta[j].y + motorG.numNodesY * myobject.vehiculos[i].ruta[j].x];   // obtener el nodo                           
            motorG.vehicleArray[i].ruta.push(node);   //ingresar el nodo     
        }
        for (var j = 0; j < myobject.vehiculos[i].pedidos.length; j++) {
            motorG.vehicleArray[i].pedidos.push(new Pedido(myobject.vehiculos[i].pedidos[j].x,myobject.vehiculos[i].pedidos[j].y,myobject.vehiculos[i].pedidos[j].cp,myobject.vehiculos[i].pedidos[j].minutosRestantes,myobject.vehiculos[i].pedidos[j].idPedido));
        }
    }
    motorG.pedidoArray =[];
    for(var i=0;i< myobject.pedidos.length;i++){
        orden = new Pedido(myobject.pedidos[i].x*motorG.nodeDistance,myobject.pedidos[i].y*motorG.nodeDistance,myobject.pedidos[i].cp,myobject.pedidos[i].idPedido);
        motorG.pedidoArray.push(orden);
    }
    motorG.bloqueoArray =[]; // bloqueo
    for(var i=0;i< myobject.bloqueos.length;i++){
        bloqueo = new Bloqueo(myobject.bloqueos[i].x*motorG.nodeDistance,myobject.bloqueos[i].y*motorG.nodeDistance);
        motorG.bloqueoArray.push(bloqueo);
    }
    motorG.incidenciaArray =[]; // incidencia
    for(var i=0;i< myobject.incidencias.length;i++){
        incidencia = new Incidencia(myobject.incidencias[i].x*motorG.nodeDistance,myobject.incidencias[i].y*motorG.nodeDistance);
        motorG.incidenciaArray.push(incidencia);
    }
    motorG.reloj = [];
    motorG.fecha = [];
    //motorG.reloj[0] = "00:00";
    motorG.fecha[0] = myobject.fecha;
    motorG.reloj[0] = myobject.reloj;    
    motorG.diasSimulados = myobject.diasSimulados;
}

var xmlhttp;
var idCarro="";
var idPedido="";
var idCliente="";
        
function loadXMLDoc(url,funcion){
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else{// code for IE6, IE5
	  	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	url="actualizaPosRuta.htm";
        url+="?idCarro=";
        if (idCarro!=="") {
            url+= idCarro;
        } else {
            url+="";
        }
        url+="&idPedido=";
        if (idPedido!=="") {
            url+= idPedido;
        }else {
            url+="";
        }
        url+="&idCliente=";
        if (idCliente!=="") {
            url+= idCliente;
        }else {
            url+="";
        }


	xmlhttp.onreadystatechange=funcion;
	//alert('aca1');
	xmlhttp.open("GET",url,true);
	//alert('aca2');
	xmlhttp.send();
}


function llamaActualizaPos(){
    if ($("#velocidadReloj").attr("value") != null  && $("#velocidadReloj").attr("value")==0) return;
    loadXMLDoc("ruta.jsp",function(){
      	//alert('aca3');
      	if (xmlhttp.readyState===4 && xmlhttp.status===200){
                    //alert('aca4');
                    var responseText =xmlhttp.responseText;
                    //myJSONObject = eval('(' + responseTxt + ')');
                    //funcionLlena(responseTxt);
                    procesandoData(responseText);
      	}
    });
}

function updatePositions(){
    if(inicio){
        llamaActualizaPos();
	motorG.vehicleCanvas.clearCanvas();
	motorG.vehicleCanvas.clearCanvas();
	visualizer.drawUpdates();
    }
}

